package com.heima.wemedia.filter;

import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import com.netflix.client.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;

@Component
@WebFilter(filterName = "wmTokenFilter", urlPatterns = "/*")
@Order(1)
@Slf4j
public class WmTokenFikter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求头中的id
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String headers = request.getHeader("userId");
        if (StringUtils.isNotBlank(headers)) {
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(headers));
            WmThreadLocalUtils.setUser(wmUser);
            log.info("用户id{},访问当前服务", headers);
        }
        //放行请求
        filterChain.doFilter(servletRequest, servletResponse);
        //清空信息
        WmThreadLocalUtils.clear();
    }
}
